package com.wang.mandkey.net;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.wang.mandkey.App;
import com.wang.mandkey.utils.ProjectEnvironment;

/**
 * 
 * @author wang 下午09:33:09-2011 TODO 拉取pc段屏幕截图线程
 */
public class ScreenPuller implements Runnable {

	private IScreenPuller mIScreenPuller = null;
	private Socket mSocket = null;
	private InputStream mInputStream = null;
	private BufferedInputStream bInputStream;
	private DataOutputStream mOutputStream = null;
	private String tag = "ScreenPuller";
	private Thread thread = null;
	private boolean isAlive = true;
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static int byte_distance=1024*64;//假设25k大小的时候取一回;
	private static int cache_size=1024*256;
	private ByteArrayOutputStream byo = new ByteArrayOutputStream(cache_size);
	private byte[] end = { 19, 87, 11 };
	public ScreenPuller(IScreenPuller iScreenPuller) {
		
		this.mIScreenPuller = iScreenPuller;
		try {
			this.mSocket = new Socket(
					InetAddress.getByName(ProjectEnvironment.STRING_HOST_IP),
					ProjectEnvironment.INT_DEFAULT_PORT_IMG);
			this.mInputStream = this.mSocket.getInputStream();
			this.bInputStream = new BufferedInputStream(this.mInputStream);// 缓存流,注意与读取方案
			this.mOutputStream = new DataOutputStream(mSocket.getOutputStream());
			String dimen = ProjectEnvironment.YOUR_PHONE_DIMEN + ":"
					+ App.screenWidth + ":" + App.screenHeight + "";
			this.mOutputStream.write(dimen.getBytes());
			thread = new Thread(this);
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
			Log.i(tag, "ScreenPuller:" + e.getMessage());
		}
	}

	@Override
	public void run() {

		byte[] buf = new byte[8192];
		int bytesize_last=0;
		Log.i(tag, "接受图片开始");
		while (isAlive) {
			try {
					int ret = this.bInputStream.read(buf);
					if (-1 != ret) {
						byo.write(buf, 0, ret);
						Log.i(tag, "接受数据大小:"+ret);
					}
					int distance=byo.size()-bytesize_last;
					if(Math.abs(distance)>byte_distance){
						//和上一次数据大小相差byte_distance KB才进行检测
						Bitmap screeMap = getBitmapBytes();
						if(null!=screeMap){
							this.mIScreenPuller.OnFinishPullScreenBitmap(screeMap);
							Date d=new Date();
							Log.e(tag, "取得桌面数据:"+sdf.format(d));
						}
						bytesize_last=byo.size();
					}
					
					
				// ====不使用缓存读取方案开始
				// int data = this.mInputStream.read();
				// if (-1 != data) {
				// if (data == end[0]) {
				// int data2 = this.mInputStream.read();
				// if (data2 == end[1]) {
				// int data3 = this.mInputStream.read();
				// if (data3 == end[2]) {
				// byte[] imgData = byo.toByteArray();
				// bitmap = BitmapFactory.decodeByteArray(imgData,
				// 0,imgData.length);
				// if (imgData.length > 0) {
				// this.mIScreenPuller.OnFinishPullScreenBitmap(bitmap);
				// Date d=new Date();
				// Log.i(tag, "一幅图片接受完成!"+sdf.format(d));
				// byo.flush();
				// byo.reset();
				// } else {
				// this.mIScreenPuller.OnFinishPullScreenBitmap(null);
				// }
				// } else {
				// byo.write(data);
				// byo.write(data2);
				// byo.write(data3);
				// }
				// } else {
				// byo.write(data);
				// byo.write(data2);
				// }
				// } else {
				// byo.write(data);
				// }
				// }
				// ===不适用缓存方案结束

				// ====使用缓存方案开始
				// this.mInputStream.read(buf);
				// this.bInputStream.read(buf);
				// if (buf[0] == ProjectEnvironment.BYTE_ENDDATA[0]
				// && buf[1] == ProjectEnvironment.BYTE_ENDDATA[1]
				// && buf[2] == ProjectEnvironment.BYTE_ENDDATA[2]) {
				//
				// byte[] imgData = byo.toByteArray();
				// bitmap = BitmapFactory.decodeByteArray(imgData, 0,
				// imgData.length);
				// if (imgData.length > 0) {
				// this.mIScreenPuller.OnFinishPullScreenBitmap(bitmap);
				// Log.i(tag, "一幅图片接受完成!");
				// byo.flush();
				// byo.reset();
				// } else {
				// this.mIScreenPuller.OnFinishPullScreenBitmap(null);
				// }
				// } else {
				// byo.write(buf, 0, buf.length);
				// Log.i(tag, "接受到了桌面数据....");
				// }
				// ====使用缓存方案结束
			} catch (IOException e) {
				e.printStackTrace();
				this.mIScreenPuller.OnInterceptedScreen(this.tag);
				Log.e(tag, "error:" + e.getMessage());
				Log.i(tag, "接受桌面数据异常....");
				break;
			}
		}

	}

	public void killSelf() {
		this.isAlive = false;
	}


	/**
	 * 从缓冲池中取走数据
	 */
	public Bitmap getBitmapBytes() {
		try {
			byte[] data = byo.toByteArray();
			if (data.length > 3) {
				for (int i = 0; i < data.length - 3; i++) {
					byte fisrt19 = data[i];
					byte second87 = data[i + 1];
					byte third11 = data[i + 2];
					if ((fisrt19 == end[0]) && (second87 == end[1])&& (third11 == end[2])) {
						// 取走标志位前面的数据
						byte[] dest = new byte[i];
						System.arraycopy(data, 0, dest, 0, i);
						//清空
						byo.flush();
						byo.reset();
						//再把剩余的数据还回去
						byo.write(data, i + 3, data.length - (i + 3));
						Bitmap tempScreen = BitmapFactory.decodeByteArray(data, 0, dest.length);
						return tempScreen;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(tag, "在 getBitmapBytes 方法中获取图片出错!");
			return null;
		}
		return null;
	}
}
